package net.stogi.unicore.beyond.ui.client.taskeditor.propertyeditor;

import net.stogi.common.gwt.dispatch.client.core.ActionManager;
import net.stogi.common.gwt.frame.client.core.EventBus;
import net.stogi.common.gwt.frame.client.mvp.AbstractPresenter;
import net.stogi.common.mvp.core.behavior.Behavior;
import net.stogi.unicore.beyond.api.model.PropertyType;
import net.stogi.unicore.beyond.api.model.PropertyValue;

class PropertyEditorPresenter extends AbstractPresenter {

	private PropertyEditorView propertyEditorView;

	private PropertyValue property;

	public PropertyEditorPresenter(PropertyEditorView propertyEditorView, ActionManager actionManager, EventBus eventBus) {
		super(actionManager, eventBus);
		this.propertyEditorView = propertyEditorView;
		initBehavior();
		initHandlers();
	}

	@Override
	protected void initBehavior() {
		// Click on 'cancel' action.
		propertyEditorView.setCancelBehavior(new Behavior() {
			
			@Override
			public void behave() {
				property = null;
				propertyEditorView.disapper();
			}
		});
		// Click on 'ok' action.
		propertyEditorView.setOkBehavior(new Behavior() {
			
			@Override
			public void behave() {
				property.setValue(propertyEditorView.collectPropertyValue());
				eventBus.fireEvent(new PropertyChangedEvent(property));
				property = null;
				propertyEditorView.disapper();
			}
		});
	}

	@Override
	protected void initHandlers() {
		eventBus.addHandler(OpenPropertyEditorEvent.TYPE, new OpenPropertyEditorHandler() {

			@Override
			public void onOpenPropertyEditor(OpenPropertyEditorEvent event) {
				property = event.getProperty();
				PropertyType propertyType = property.getPropertyType();
				propertyEditorView.displayProperty(propertyType.getKey(), propertyType.getValueType(), property.getValue());
			}
		});
	}
}
